package com.pine.service.pineframework.impl;

import cn.hutool.core.util.IdUtil;
import com.pine.common.beans.exception.BusinessException;
import com.pine.common.beans.exception.ExceptionCodeEnum;
import com.pine.common.beans.pineframework.request.SysAuthValidateCaptchaCodeRequest;
import com.pine.common.beans.pineframework.response.SysAuthGetCaptchaCodeResponse;
import com.pine.common.captcha.CaptchaClient;
import com.pine.common.captcha.core.CaptchaCodeInfo;
import com.pine.common.redis.config.RedissonClientUtil;
import com.pine.service.pineframework.SysAuthService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 系统认证 服务实现类
 * </p>
 *
 * @author pine manage
 * @since 2024-08-21
 */
@Service
public class SysAuthServiceImpl implements SysAuthService {

    @Resource
    private CaptchaClient captchaClient;

    /**
     * 获取验证码
     *
     * @return 验证码信息
     */
    @Override
    public SysAuthGetCaptchaCodeResponse getCaptchaCode() {
        CaptchaCodeInfo captchaCode = captchaClient.getCaptchaCode();
        SysAuthGetCaptchaCodeResponse response = new SysAuthGetCaptchaCodeResponse();

        // 设置redis缓存
        String cacheKey = IdUtil.getSnowflakeNextIdStr();
        RedissonClientUtil.setCacheWithExpiration(CaptchaCodeInfo.CACHE_KEY + cacheKey, captchaCode.getCaptchaKey(), captchaCode.getExpireTime());

        response.setCaptchaKey(cacheKey);
        response.setCaptchaBase64(captchaCode.getCaptchaBase64());
        response.setExpireTime(captchaCode.getExpireTime());
        return response;
    }

    /**
     * 校验验证码
     *
     * @param request 校验验证码请求体
     * @return 校验结果
     */
    @Override
    public Boolean validateCaptchaCode(SysAuthValidateCaptchaCodeRequest request) {
        Object captchaCode = RedissonClientUtil.getCache(CaptchaCodeInfo.CACHE_KEY + request.getCaptchaKey());
        // 从redis 获取验证码为空时抛出异常
        if (Objects.isNull(captchaCode)) {
            throw new BusinessException(ExceptionCodeEnum.CAPTCHA_EXPIRED);
        }

        // 校验验证码
        if (!captchaClient.verifyCaptchaCode(captchaCode.toString(), request.getCaptchaCode())) {
            throw new BusinessException(ExceptionCodeEnum.CAPTCHA_ERROR);
        }

        // 验证码校验通过后删除redis缓存
        RedissonClientUtil.removeCache(CaptchaCodeInfo.CACHE_KEY + request.getCaptchaKey());
        return true;
    }
}
